<template>
<div class="playlist-panel">
  <div class="player-style" ref="playerRef" :style="{width:'100%',height:playerHeight+'px'}"></div>
    <div class="danum-panel">
      <div class="watcher">
        {{onLineCount}} 人正在观看,已装填 {{danmuCount}} 条弹幕
      </div>
      <div id="danum" class="danum" v-show="showDanmu"></div>
      <div class="close-danmu" v-show="!showDanmu">该视频已关闭弹幕</div>
      <div id="paly"><img src="@/assets/images/play.png"></div>
    </div>
</div>
</template>
<script setup>
import {computed, getCurrentInstance, inject, nextTick, onMounted, onUnmounted, ref, watch} from "vue";
import {useRoute, useRouter} from "vue-router";
import {mitter} from "@/eventbus/eventBus.js";
import Hls from "hls.js";
import ArtPlayer from "artplayer";
import artplayerPluginDanmuku from "artplayer-plugin-danmuku";
import {useLoginStore} from "@/stores/loginStore.js";
import {ImgURL} from "@/utils/Request.js";
import {AddWatch, GetLoadDanmu, LoadWatch, PostLoadDanmu} from "@/api/video.js";
import ElementPlus, {ElMessage} from "element-plus";
import loadWatch from "@/data/loadWatch.json";
import video_Nodata from "@/data/video_Nodata.json";
import video_LoadDanmu from "@/data/video_LoadDanmu.json";

const {proxy} = getCurrentInstance();
const route = useRoute();
const router = useRouter();
const loginStore = useLoginStore();

const playerRef = ref();
let player = null;

const initPlayer = () => {
  ArtPlayer.CONTEXTMENU = false;
  ArtPlayer.AUTO_PLAYBACK_MAX = 20;
  ArtPlayer.AUTO_PLAYBACK_MIN = 10;

  player = new ArtPlayer({
    container: playerRef.value,
    url: '',
    poster: '',
    type: 'm3u8',
    lang: 'zh-cn',
    contextmenu: [
      {
        name: 'pinke',
        html: 'pinke',
        click: function () {
          player.contextmenu.show = false;
        },
      },
    ],
    customType: {
      m3u8: function(video, url, art) {
        if (Hls.isSupported()) {
          if (art.hls) art.hls.destroy();
          const hls = new Hls();
          hls.loadSource(url);
          hls.attachMedia(video);
          art.hls = hls;
          art.on('canplay', function() {
            if (art.hls) art.hls.startLoad();
          });
        } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
          video.src = url;
        } else {
          alert('您的浏览器不支持HLS播放');
          return false;
        }
      }
    },
    theme: '#23ade5',
    volume: 0.7,
    isLive: false,// 是否是直播
    muted: false, // 设置视频为静音
    autoplay: true,// 自动播放
    pip: true,// 画中画
    autoSize: true,// 自动全屏
    autoMini: true,// 自动小屏
    screenshot: true,// 截图
    setting: true,// 设置
    loop: false,// 循环播放
    flip: true,// 画面翻转
    playbackRate: true,// 播放速度
    aspectRatio: false,// 宽高比
    fullscreen: true,// 全屏
    fullscreenWeb: true,// 网页全屏
    subtitleOffset: true,// 字幕偏移
    miniProgressBar: true,// 迷你进度条
    mutex: true,// 互斥
    backdrop: true,// 背景遮罩
    playsInline: true,// 画中画
    autoPlayback: true,// 自动播放
    airplay: true,// 投屏
    icons: {
      state: document.querySelector('#paly')
    },
    controls: [
      {
        name: 'wide-screen',
        position: 'right',
        html: '<span class="iconfont icon-wide-screen"></span>',
        tooltip: '宽屏模式',
        style: {
          color: '#fff'
        },
        click: function(...args) {
          changeWideScreen();
        }
      },
      {
        name: 'narrow-screen',
        position: 'right',
        html: '<span class="iconfont icon-narrow-screen"></span>',
        tooltip: '退出宽屏',
        style: {
          color: '#fff',
          display: 'none' // 初始状态不显示
        },
        click: function(...args) {
          changeWideScreen();
        }
      }
    ],
    plugins: [
      artplayerPluginDanmuku({
        mount: document.querySelector('#danum'),
        theme: 'light',
        emitter: true,
        danmuku:function() {
          return new Promise(async (resolve) => {
            let danmuList = [];
            danmuList = await loadDanmu();
            return resolve(danmuList);
          })
        },
        beforeEmit: async (danmu) => {
          // 配置违禁词
          const forbiddenWords = ['TM', '2B', 'SB', 'sb','2b'];
          for (let word of forbiddenWords) {
            if (danmu.text.includes(word)) {
              ElMessage.error("包含违禁词，弹幕发送失败");
              return false; // 不发送该弹幕
            }
          }
          // 发送弹幕到服务器
          const res = video_Nodata;
          ElMessage.warning(res.message);
        }
      })
    ]
  });
  player.on('hover', (state) => {
    let display = 'none';
    if (state) {
      display = 'flex';
    }
    player.template.$bottom.style.display = display;
  });

  player.on('video:ended', (e) => {
      mitter.emit('playEnd');
  });

  // 监听error事件
  player.on('error', (err) => {
    if(err.type === 'MEDIA_ERR_SRC_NOT_SUPPORTED' || err.type === 'MEDIA_ERR_NETWORK' || err.message.includes('timeout')){
      ElMessage.error("视频加载失败，请稍后再试！");
    }
  });
};
const fileId = ref();
const danmuCount = ref(0);
const onLineCount = ref(0);
const playerHeight = ref(500);
const setPlayerHeight = inject("playerHeight")
const loadDanmu = async () => {
  if(!fileId.value){
    return[];
  }
  const res = video_LoadDanmu;
  let loads = [];
  for(let i = 0;i<res.data.length;i++){
    let load = {
      text: res.data[i].bnr, // 弹幕文本
      time: res.data[i].time, // 弹幕时间, 默认为当前播放器时间
      mode: res.data[i].mode, // 弹幕模式: 0: 滚动(默认)，1: 顶部，2:
      color: res.data[i].color, // 弹幕颜色，默认为白色
      border: false, // 弹幕是否有描边, 默认为 false
      style: {}, // 弹幕自定义样式, 默认为空对象
    };
    loads.push(load)
  }
  mitter.emit('loadDanmu',res.data);
  danmuCount.value = loads.length;
  return loads;
}
//调整player播放进度
mitter.on('playerCurrentTime',(time)=>{
  player.currentTime = time;
})
//播放器鼠标右键
mitter.on('showAlert',()=>{
  player.contextmenu.show = true;
})
//监听浏览器窗口大小变化
window.addEventListener('resize', () => {
  setHeight();
});
const setHeight = () => {
  const width = window.innerHeight;
  const height = Math.round(width+500)*0.41;
  if(height < 500){
    mitter.emit('playerheight',400);
    playerHeight.value = 400;
    setPlayerHeight(400);
    return;
  }
  mitter.emit('playerheight',height);
  playerHeight.value = height;
  setPlayerHeight(height);
}
onMounted(() => {
  nextTick(() => {
    initPlayer();
    setHeight();
  });
  mitter.on('changeP',(_file)=>{
    if(_file.length === 0){
      return;
    }
    fileId.value = _file[0];
    player.switch = `${ImgURL}/m3u8/${_file[1]}`
    player.plugins.artplayerPluginDanmuku.load();
    player.mute(false);
  })
});
//宽屏切换事件
const emit = defineEmits(['changeWideScreen']);
const WideScreen = ref(false);
const changeWideScreen = () => {
  WideScreen.value = !WideScreen.value;
  if (WideScreen.value) {
   player.controls['wide-screen'].style.display = 'none';
   player.controls['narrow-screen'].style.display = 'flex';
  } else {
    player.controls['wide-screen'].style.display = 'flex';
   player.controls['narrow-screen'].style.display = 'none';
  }
  emit('changeWideScreen', WideScreen.value);
}
//每5秒 更新弹幕
const timer = setInterval(() => {
  if(showDanmu.value){
    player.plugins.artplayerPluginDanmuku.load();
  }
}, 15000);
const getLoadWatch = async () => {
  const res = loadWatch;
  onLineCount.value = res.data;
}

const videoInfo = inject("videoInfo");
const showDanmu = computed(() => {
  return !(videoInfo.value.interaction == null||videoInfo.value.interaction.indexOf("0")==-1);
});

onMounted(() => {
  getLoadWatch();
});
onUnmounted(() => {
  clearInterval(timer);
});
</script>
<style scoped lang="scss">
.playlist-panel{
  width: 100%;
  :deep(.art-video-player .art-mask-show .art-state){
    //按钮
    position: absolute;
    right: 40px;
    bottom: 40px;
    .art-icon-state{
      width: 60px;
      height: 60px;
      img{
        width: 100%;
      }
    }
  }
  :deep(.art-state){
    cursor: pointer;
    right: 15px;
    bottom: 20px;
    position: absolute;
  }
  :deep(.art-controls-right){
    position: relative;
    display: block;
    width: 280px;

    .art-control{
      position: absolute;
    }

    .art-control-screenshot{
      left: 0;
    }
    .art-control-setting{
      left: 46px;
    }
    .art-control-pip{
      left: 92px;
    }

    .art-control-wide-screen,
    .art-control-narrow-screen{
      left: 138px;
      .iconfont{
        font-size: 20px;
      }
    }
    .art-control-fullscreenWeb{
      left: 184px;
    }
    .art-control-fullscreen{
      left: 230px;
    }
  }
}
:deep(.danum-setting){
  background: none !important;
  padding: 0;
  border: none !important;
  .inner-panel{
    width: 300px;
    height: 280px;
    position: relative;
    .inner{
      position: absolute;
      left: 0;
      top: 0;
      z-index: 99999;
      color: #fff;
    }
    .mask{
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      top: 0;
      background: #000;
      opacity: .6;
    }
  }
}
:deep(.art-video-player){
  height: 100% !important;
  width: 100% !important;
}
.danum-panel{
  box-shadow: 0 2px 6px #ddd;
  display: flex;
  height: 56px;
  border-top: none;
  background: #fff;
  align-items: center;
  padding: 15px;
  .watcher{
    flex: 0.3;
    color: #666;
    margin-top: -5px;
    padding-bottom: 10px;
    font-size: 14px;
    padding-left: 10px;
    padding-top: 10px;
  }
  .danum{
    flex: 1;
    font-size: 12px;
  }
  .close-danmu{
    color: #666;
    text-align: center;
  }
}

//浏览器大小 适配
@media screen and (max-width: 1580px) {
  .danum-panel .danum{
    flex: 0.7;
  }
}
@media screen and (max-width: 1300px) {
  .danum-panel {
    .watcher{
      flex: 1.5;
    }
    .danum{
      flex: 1;
    }
  }
}
</style>